package com.frp.lib.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.IOException;

/**
 * Created by hujianjun on 11/22 0022.
 */
public class JSON {
    private static ObjectMapper objectMapper = new ObjectMapper();
    static {
        objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    }
    public static String toJson(Object object) {
        try {
            String json = objectMapper.writeValueAsString(object);
            return json;
        } catch (JsonProcessingException e) {
            return null;
//            e.printStackTrace();
        }
    }

    public static byte[] toJsonBytes(Object object) {
        try {
            byte[] content = objectMapper.writeValueAsBytes(object);
            return content;
        } catch (JsonProcessingException e) {
            return null;
        }
    }

    public static <T> T fromJson(String json, Class<? extends T> clazz) {
        try {
            T value = objectMapper.readValue(json, clazz);
            return value;
        } catch (IOException e) {
            return null;
//            e.printStackTrace();
        }
    }

    public static <T> T fromJsonBytes(byte[] data, Class<? extends T> clazz) {
        try {
            T value = objectMapper.readValue(data, clazz);
            return value;
        } catch (IOException e) {
            return null;
//            e.printStackTrace();
        }
    }
}
